using SmartCommunity.Models;
using Mapster;
using Microsoft.EntityFrameworkCore;

namespace SmartCommunity.WebApi.Services.System
{
    /// <summary>
    /// 服务类：数据字典
    /// </summary>
    public class DictService : BaseService<DictEntity>
    {
        #region 构造函数
        protected readonly SCDBContext ctx;
        public DictService(SCDBContext ctx)
        {
            this.ctx = ctx;
        }
        #endregion

        #region 数据查询 
        /// <summary>
        /// 分页查询
        /// </summary>
        public async Task<PageResult<DictDto>> FindPagedList(DictQuery dictQuery, Pager pager, LoginUser user)
        {
            var query = ctx.Dicts.AsNoTracking().Where(dictQuery.GetQueryExpression());
            var data = await FindPagedList(query, pager, o => o.OrderByDescending(t => t.CreatedTime));
            return data.Map(o => o.Adapt<DictDto>());
        }
        public async Task<List<DictItemDto>> FindExportList(DictQuery query, LoginUser user)
        {
            var lstDicts = await ctx.Dicts.Include(a => a.DictItems).OrderByDescending(t => t.CreatedTime)
                .AsNoTracking().Where(query.GetQueryExpression()).ToListAsync();
            return lstDicts.SelectMany(a =>
            {
                return a.DictItems.OrderBy(a => a.SortNo).Select(t =>
                {
                    t.Dict = a; return t.Adapt<DictItemDto>();
                });
            }).ToList();
        }

        /// <summary>
        /// 根据数据字典ID查询
        /// </summary>
        public async Task<DictDto> FindDictById(int dictId)
        {
            var entity = await FindById(dictId);
            return entity.Adapt<DictDto>();
        }

        /// <summary>
        /// 根据ID查询实体类
        /// </summary>
        private async Task<DictEntity> FindById(int id)
        {
            return await ctx.Dicts.Include(a=>a.DictItems).SingleOrDefaultAsync(a => a.DictId == id)
                ?? throw new NotFoundException($"找不到指定的数据字典,Id:{id}");
        }
        #endregion

        #region 增 删 改
        /// <summary>
        /// 新增数据字典
        /// </summary>
        public async Task<DictDto> CreateDict(DictDto dto, LoginUser user)
        {
            // 新建对象
            var entity = new DictEntity();
            // 复制属性
            await CopyDtoToEntity(dto, entity, user, true);
            // 执行保存
            ctx.Dicts.Add(entity);
            await ctx.SaveChangesAsync();
            // 返回Dto
            return entity.Adapt<DictDto>();
        }

        /// <summary>
        /// 更新数据字典
        /// </summary>
        public async Task UpdateDict(DictDto dto, LoginUser user)
        {
            // 原始数据
            var entity = await FindById(dto.DictId);
            // 更新字段
            await CopyDtoToEntity(dto, entity, user, false);
            // 执行更新
            await ctx.SaveChangesAsync();
        }

        /// <summary>
        /// 复制dto属性到实体字段
        /// </summary>
        private async Task CopyDtoToEntity(DictDto dto, DictEntity entity, LoginUser user, bool isNew)
        {
            // 检查数据重复
            if (await ctx.Dicts.AnyAsync(a => a.DictId != dto.DictId && (a.DictType == dto.DictType || a.DictName == dto.DictName)))
            {
                throw new MessageException("当前已存在相同名称或编码的数据字典");
            }
            entity.DictType = dto.DictType;
            entity.DictName = dto.DictName;
            entity.Remark = dto.Remark;

            // 记录操作人
            if (isNew)
            {
                entity.CreatedBy = user.Username;
                entity.CreatedTime = DateTime.Now;
            }
            entity.UpdatedBy = user.Username;
            entity.UpdatedTime = DateTime.Now;
        }

        /// <summary>
        /// 根据ID删除数据字典
        /// </summary>
        public async Task DeleteByIds(IEnumerable<int> ids, LoginUser user)
        {
            var lstData = await ctx.Dicts.Include(a => a.DictItems).Where(a => ids.Contains(a.DictId)).ToListAsync();
            if (lstData.Count != ids.Count())
            {
                throw new MessageException("查询出的数据和传入的ID不匹配，请刷新后再试。");
            }
            foreach (var entity in lstData)
            {
                ctx.DictItems.RemoveRange(entity.DictItems);
                ctx.Dicts.Remove(entity);
            }
            // 提交事务
            await ctx.SaveChangesAsync();
        }
        #endregion
    }
}
